package com.liu;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Random;
import java.util.TimeZone;

/**
 *
 */
@Slf4j
@EnableScheduling
@SpringBootApplication
public class MonitorCaptureApplication {

    @Value("${my.time}")
    private Long time;

    @Value("${my.savePath}")
    private String savePath;

    @Value("${my.sourcePath}")
    private String sourcePath;

    private static final SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd-HHmmss");
    private static final SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMdd");

    public static void main(String[] args) {
        SpringApplication.run(MonitorCaptureApplication.class, args);
    }

    @Scheduled(fixedDelayString = "${my.interval}")
    public void doWork() {
        try {
            long startTime = System.currentTimeMillis();
            log.info("current timestamp：[{}]", startTime);
            File file = new File(savePath + "/" + getPath());
            if (!file.exists()) {
                file.mkdirs();
            }
            Process process = Runtime.getRuntime().exec("ffmpeg -y -t " + time + " -i " + sourcePath +" -an -vcodec copy -f mp4 " + savePath + "/" + getPath() + "/" + getRandomName());
            while (process.isAlive()) {
                InputStream inputStream = process.getErrorStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    log.info(line);
                }
            }
            process.destroy();
            log.info("spend：[{}]ms", System.currentTimeMillis() - startTime);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取mp4的文件名
     * @return /
     */
    public static String getPath() {
        Calendar instance = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("GMT")));
        return df2.format(instance.getTime());
    }

    /**
     * 获取mp4的文件名
     * @return /
     */
    public static String getRandomName() {
        Calendar instance = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("GMT")));
        String date = df1.format(instance.getTime());
        int random = BigDecimal.valueOf(new Random().nextFloat()).multiply(new BigDecimal(10000)).intValue();
        return date + "-" + random + ".mp4";
    }

}
